import { Notice, Plugin, TFile, TFolder, Modal } from "obsidian";

class NoteCreationModal extends Modal {
	noteName: string;
	onSubmit: (noteName: string) => void;

	constructor(app: any, onSubmit: (noteName: string) => void) {
		super(app);
		this.onSubmit = onSubmit;
	}

	onOpen() {
		const { contentEl,titleEl } = this;

		const title = titleEl.createEl("div", { text: "创建笔记目录" });
		title.className = 'modal-title'

		contentEl.createEl("p", { text: "请输入笔记目录名称:" });
		
		const input = contentEl.createEl("input", { type: "text" });
		input.className = "modal-create-note-input";
		input.focus();

		const buttonContainer = contentEl.createEl("div");
		buttonContainer.className = "modal-button-container";


		const createButton = buttonContainer.createEl("button", {
			text: "创建",
			type: "button",
		});
		createButton.className = "mod-cta";
		createButton.onclick = () => {
			this.noteName = input.value.trim();
			if (this.noteName) {
				this.onSubmit(this.noteName);
				this.close();
			} else {
				new Notice("笔记目录名称不能为空");
			}
		};


		const cancelButton = buttonContainer.createEl("button", {
			text: "取消",
		});
		cancelButton.onclick = () => this.close();


		this.scope.register([], "Enter", (evt: KeyboardEvent) => {
			if (evt.isComposing) {
				return;
			}

			this.noteName = input.value.trim();
			if (this.noteName) {
				this.onSubmit(this.noteName);
				this.close();
			} else {
				new Notice("笔记目录名称不能为空");
			}
		});

	}

	onClose() {
		const { contentEl } = this;
		contentEl.empty();
	}
}

export default class ObsidianCreateNoteMenuPlugin extends Plugin {
	async onload() {
		this.app.workspace.on("file-menu", (menu: any, file) => {
			if (file instanceof TFolder) {
				menu.addItem((item: any) => {
					item.dom.id = "addNoteFolder";
					item.setTitle("创建笔记目录")
						.setIcon("folder-plus")
						.onClick(() => {
							new NoteCreationModal(
								this.app,
								async (noteName) => {
									try {
										const newFolder =
											await this.app.vault.createFolder(
												`${file.path}/${noteName}`
											);

										const newNote =
											await this.app.vault.create(
												`${newFolder.path}/${noteName}.md`,
												``
											);

										this.refreshFileExplorer();

										await this.openFile(newNote);

										new Notice(`创建笔记目录: ${noteName}`);
									} catch (error) {
										new Notice(
											`创建笔记目录失败: ${error.message}`
										);
									}
								}
							).open();
						});
				});

				setTimeout(() => {
					const menuEl = menu.scrollEl;
					if (!menuEl) return;

					const menuItemEl = menuEl.querySelector('#addNoteFolder');
					menuEl.insertBefore(menuItemEl, menuEl.firstChild);
					const separator = document.createElement('div');
					separator.className = 'menu-separator';
					menuEl.insertBefore(separator, menuItemEl.nextSibling);
				}, 1);
			}
		});
	}

	refreshFileExplorer() {
		const fileExplorer =
			this.app.workspace.getLeavesOfType("file-explorer")[0];
		if (fileExplorer) {
			fileExplorer.view.containerEl.classList.add("force-refresh");
			setTimeout(() => {
				fileExplorer.view.containerEl.classList.remove("force-refresh");
			}, 10);
		}
	}

	async openFile(file: TFile) {
		const leaf = this.app.workspace.getLeaf("tab");
		await leaf.openFile(file);
	}
}
